package com.by.basicservice.controller;

import com.alibaba.fastjson2.JSON;
import com.by.toolkit.model.Resp;
import com.by.toolkit.utils.OkHttpUtil;
import com.by.toolkit.utils.SplitterUtil;
import com.by.toolkitspring.offline.OfflineSpi;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ServiceLoader;

import static com.by.toolkit.utils.ExceptionUtil.getStackTrace;

/**
 * 服务下线
 *
 * @author YanBingHao
 * @since 2025/9/29
 */
@Slf4j
@RequestMapping
@RestController
public class DubboRegisterController {


    private static final String LOCAL_HOST_URL = "http://127.0.0.1";

    @Value("${dubbo.application.qos-port}")
    private String port;

    @GetMapping("/nacosDeregister")
    public Resp<Void> nacosDeregister() {
        ServiceLoader<OfflineSpi> offlines = ServiceLoader.load(OfflineSpi.class);
        try {
            offlines.forEach(offline -> {
                try {
                    offline.offline();
                } catch (Exception e) {
                    log.warn("[DubboRegisterController][nacosDeregister] offline:[{}] hasException:[{}] ", offline.getClass().getSimpleName(), getStackTrace(e));
                }
            });
            String result = OkHttpUtil.post(SplitterUtil.EN_COLON_JOINER.join(LOCAL_HOST_URL, port) + "/byOffline", Maps.newHashMap(), Maps.newHashMap(), Maps.newHashMap(), String.class, OkHttpUtil.getInstance());
            log.info("[DubboRegisterController][nacosDeregister] Dubbo 下线完成,result:{}", JSON.toJSONString(result));
        } catch (IOException e) {
            log.error("[DubboRegisterController][nacosDeregister] Dubbo qos下线异常:{}", getStackTrace(e));
        }
        return Resp.ok();
    }
}
